//*************************************************************************************
//* 作    者： 邹杭特
//* 创建时间： 2021-09-25 05:29:41
//* 描    述：  

//* ************************************************************************************
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;

/// <summary>
/// UIScript对象
/// <summary>
public class TeachUIBehaviour : MonoBehaviour
{
    [SerializeField]
    protected Button m_hideBtn;
    [SerializeField]
    protected Image m_maskImage;
    [SerializeField]
    protected Text m_stepNameText;

    protected Vector3[] m_cornors = new Vector3[4];
    protected Vector4 m_rectPos = Vector4.zero;
    protected Material m_material;
    protected RectTransform m_targetTrans;
    protected int m_focusTimer;
    protected float m_startTime;
    protected Vector3 m_worldPos;
    protected float m_redios;
    protected string teachType;
    protected float m_delyTime;
    protected string m_guidingText;
    protected int m_guidingTextId;
    protected CanvasGroup m_canvasGroup;
    protected int m_delyCloseTimer;
    public static bool lookLikeCloseed;
    protected RectTransform m_hideBtnRectTransform;
    protected RectTransform m_rectTransfrom;
    private void Awake()
    {
        m_rectTransfrom = transform as RectTransform;
        m_hideBtnRectTransform = m_hideBtn.GetComponent<RectTransform>();
        m_hideBtn.onClick.AddListener(OnClickTarget);
        m_canvasGroup = GetComponent<UnityEngine.CanvasGroup>();
        m_material = m_maskImage.material;
    }

    void OnDestroy()
    {
        TimerAgent.Instance.StopTimer(m_focusTimer);
        TimerAgent.Instance.StopTimer(m_delyCloseTimer);
    }

    private void TryStartGuide(string guideText, string stepName, string teachType, float delyTime, string sourcePath, Vector3 pos)
    {
        lookLikeCloseed = false;
        if (m_delyCloseTimer > 0)
            TimerAgent.Instance.StopTimer(m_delyCloseTimer);
        if (m_focusTimer > 0)
            TimerAgent.Instance.StopTimer(m_focusTimer);

        m_startTime = Time.time;
        m_guidingTextId = 0;
        m_stepNameText.text = "";
        this.teachType = teachType;

        m_delyTime = delyTime;

        if (teachType == "hit_ui")
        {
            HideMaskPort();
            //TODO 通过sourcePath找到目标RectTransform;
            //m_targetTrans = target as RectTransform;
            m_focusTimer = TimerAgent.Instance.RegistLoop(ShowMaskByTargetTrans, 0.02f);
        }
        else if (teachType == "hit_pos")
        {
            m_worldPos = pos;
            HideMaskPort();
            m_focusTimer = TimerAgent.Instance.RegistLoop(ShowMaskByWorldPos, 0.02f);
        }
        else if (teachType == "hide_ui")
        {
            HideMaskPort();
        }
        else
        {
            Debug.LogError("error teachType:" + teachType);
            OnClickTarget();
        }
    }


    private bool ShowMaskByTargetTrans()
    {
        if (CheckDelyTimer())
            return true;

        if (!m_targetTrans)
        {
            //UIManager.Instance.CloseUI(UIDefine.UIInfo.TeachView);
            //Debug.LogError("target trans empty!");
            //GuideManager.Instance.StopGuideSystem();
            return true;
        }

        m_hideBtnRectTransform.position = m_targetTrans.position;
        m_hideBtnRectTransform.sizeDelta = m_targetTrans.rect.size;
        m_hideBtnRectTransform.gameObject.SetActive(true);
        m_canvasGroup.alpha = Mathf.Lerp(m_canvasGroup.alpha, 1, 0.5f);
        AdjustHand();
        RefreshMaterial();
        RefreshText();
        return false;
    }

    private void AdjustHand()
    {
        var revarse = m_hideBtnRectTransform.anchoredPosition.y < m_rectTransfrom.rect.size.y * 0.4f;
        if (revarse)
        {
            m_hideBtnRectTransform.localEulerAngles = new Vector3(0, 0, 180);
            m_stepNameText.transform.localEulerAngles = new Vector3(0, 0, 180);
        }
        else
        {
            m_hideBtnRectTransform.localEulerAngles = Vector3.zero;
            m_stepNameText.transform.localEulerAngles = Vector3.zero;
        }

    }

    private bool CheckDelyTimer()
    {
        float timerOffset = Time.time - m_startTime;
        if (timerOffset < m_delyTime)
        {
            return true;
        }
        else if (timerOffset > m_delyTime + 10)
        {
            TimerAgent.Instance.StopTimer(m_focusTimer);
        }
        return false;
    }

    private void RefreshMaterial()
    {
        m_rectPos.x = m_hideBtnRectTransform.localPosition.x - m_hideBtnRectTransform.sizeDelta.x * 0.5f;
        m_rectPos.y = m_hideBtnRectTransform.localPosition.y - m_hideBtnRectTransform.sizeDelta.y * 0.5f;
        m_rectPos.z = m_hideBtnRectTransform.sizeDelta.x;
        m_rectPos.w = m_hideBtnRectTransform.sizeDelta.y;
        m_material.SetVector("_Rect", m_rectPos);
    }

    private bool ShowMaskByWorldPos()
    {
        if (CheckDelyTimer())
            return true;

        Vector3 ptViewport = Camera.main.WorldToViewportPoint(m_worldPos);

        //获取父UI的长宽，注意不是Screen.Width、Screen.heigt
        RectTransform rtParent = m_hideBtnRectTransform.parent.GetComponent<RectTransform>();
        var centerPos = Vector2.zero;
        centerPos.x = rtParent.pivot.x * rtParent.rect.width;
        centerPos.y = rtParent.pivot.y * rtParent.rect.height;
        //设置锚点位置，锚点在左下角
        m_hideBtnRectTransform.anchoredPosition = new Vector2(ptViewport.x * rtParent.rect.width, ptViewport.y * rtParent.rect.height) - centerPos;
        m_hideBtnRectTransform.sizeDelta = new Vector2(m_redios, m_redios);
        AdjustHand();
        m_canvasGroup.alpha = Mathf.Lerp(m_canvasGroup.alpha, 1, 0.5f);
        m_hideBtnRectTransform.gameObject.SetActive(true);
        RefreshMaterial();
        RefreshText();
        return false;
    }

    private void RefreshText()
    {
        var timeSpan = Time.time - m_startTime - m_delyTime;
        var num = Mathf.CeilToInt(timeSpan * 10);
        num = Mathf.Clamp(num, 0, m_guidingText.Length);
        m_stepNameText.text = m_guidingText.Substring(0, num);
    }

    private void HideMaskPort()
    {
        TimerAgent.Instance.StopTimer(m_focusTimer);
        m_hideBtnRectTransform.gameObject.SetActive(false);
        m_material.SetVector("_Rect", new Vector4(-10000, -10000, 1, 1));
        m_canvasGroup.alpha = 0;
    }

    private void OnClickTarget()
    {
        PointerEventData data = new PointerEventData(EventSystem.current);
        data.position = Input.mousePosition;
        HideMaskPort();
        lookLikeCloseed = true;
        TimerAgent.Instance.StopTimer(m_delyCloseTimer);
        m_delyCloseTimer = TimerAgent.Instance.DelyExecute(() =>
        {
            if (lookLikeCloseed)
            {
                //UIManager.Instance.CloseUI(UIDefine.UIInfo.TeachView);
            }
        }, 5);
        //GuideManager.Instance.ApplyCurrentStep();
        List<RaycastResult> results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(data, results);
        GameObject current = data.pointerCurrentRaycast.gameObject;
        TeachUIBehaviour rootParent = null;
        for (int i = 0; i < results.Count; i++)
        {
            if (current != results[i].gameObject)
            {
                data.pointerClick = results[i].gameObject;

                var parentUI = data.pointerClick.gameObject.GetComponentInParent<TeachUIBehaviour>();

                if (parentUI && parentUI.gameObject == gameObject)
                {
                    continue;
                }

                if (rootParent == null)
                {
                    rootParent = parentUI;
                }
                else
                {
                    if (parentUI != rootParent)
                    {
                        break;
                    }
                }
                ExecuteEvents.Execute(results[i].gameObject, data, ExecuteEvents.pointerClickHandler);
                //RaycastAll后ugui会自己排序，如果你只想响应透下去的最近的一个响应，这里ExecuteEvents.Execute后直接break就行。
            }
        }
    }
}